﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PreguntaAlExperto.RulesLayer.Entities;
using PreguntaAlExperto.RulesLayer.Services;
using System.Net;
using System.Net.Mail;
using Common;

namespace PreguntaAlExperto
{
    public partial class publicar : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.lblMustRegister.Text = Resources.language.RegisterText;
            this.lblTitle.Text = Resources.language.ArticleTitle;
            this.lblBody.Text = Resources.language.ArticleBody;
            this.lblDescription.Text = Resources.language.ArticleShortDescription;
            this.lblPublishAnArticle.Text = Resources.language.PublishTitle;
            this.lblCategories.Text = Resources.language.PublishCategories;
            //this.lblTags.Text = Resources.language.Tags;
            this.lblTechnologies.Text = Resources.language.Technologies;
            this.lblSkillLevel.Text = Resources.language.Skills;
            this.lblPlatform.Text = Resources.language.Platform;
            this.lblLanguage.Text = Resources.language.Languages;
            this.btnPublish.Text = Resources.language.PublishButton;
            this.lblErrorCategories.Text = Resources.language.ErrorCategories;
            this.lblSendWarning.Text = Resources.language.SendWarningMessages;

            if (Session["UserID"] != null)
            {
                this.pnlMustRegister.Visible = false;
                this.pnlPublish.Visible = true;
            }
            else
            {
                this.pnlMustRegister.Visible = true;
                this.pnlPublish.Visible = false;
            }

            if (!IsPostBack)
            {
                PreguntaAlExperto.RulesLayer.Services.PairService _service = new PreguntaAlExperto.RulesLayer.Services.PairService();
                this.dtLanguage.DataSource = _service.getPairList(PairService.enuPairList.Languages);
                this.dtLanguage.DataBind();

                this.dtPlatform.DataSource = _service.getPairList(PairService.enuPairList.Platforms);
                this.dtPlatform.DataBind();

                this.dtSkill.DataSource = _service.getPairList(PairService.enuPairList.Skills);
                this.dtSkill.DataBind();

                this.dtTechnologies.DataSource = _service.getPairList(PairService.enuPairList.Technologies);
                this.dtTechnologies.DataBind();
            }
        }

        protected void btnPublish_Click(object sender, EventArgs e)
        {
            string _languages = Request.Form["chkLanguage"];
            string _skills = Request.Form["chkSkill"];
            string _platforms = Request.Form["chkPlatform"];
            string _technologies = Request.Form["chkTechnologies"];

            //if (!string.IsNullOrEmpty(_languages) &&
            //    !string.IsNullOrEmpty(_skills) &&
            //    !string.IsNullOrEmpty(_platforms) &&
            //    !string.IsNullOrEmpty(_technologies))
            //{

            //    if (_languages.Length != 0 &&
            //        _skills.Length != 0 &&
            //        _platforms.Length != 0 &&
            //        _technologies.Length != 0)
            //    {
                    if (this.txtShortDescription.Text.Trim().Length != 0 &&
                        this.txtTitle.Text.Trim().Length != 0)
                    {
                        if (this.flArticleBody.FileName.Trim().Length != 0)
                        {
                            this.lblHeaderError.Visible = false;
                            this.lblErrorCategories.Visible = false;

                            try
                            {
                                Article _article = new Article();
                                ArticlesService _service = new ArticlesService();

                                string userName = ((string)Session["LoginName"]).Replace(" ", "");
                                string title = this.txtTitle.Text.Trim();

                                string _ArticlePath = 
                                    Server.HtmlEncode(userName
                                    .Replace("&", "").Replace(";", "").Replace("#", "").Replace(" ", "")
                                    .Replace("&", "").Replace(";", "").Replace("#", ""))  + "-" +
                                    Server.HtmlEncode(title
                                    .Replace(" ", "-").Replace("&", "").Replace(";", "").Replace("#", ""))
                                    .Replace(" ",  "").Replace("&", "").Replace(";", "").Replace("#", "") + ".txt";

                                //string _ArticlePath = (userName + "-" + title).ToUrlString ();
                                string _ArticleForDB = Server.HtmlEncode(userName
                                    .Replace("&", "").Replace(";", "").Replace("#", "").Replace(" ", "")
                                    .Replace("&", "").Replace(";", "").Replace("#", "")) + "-" +
                                    Server.HtmlEncode(title
                                    .Replace(" ", "-").Replace("&", "").Replace(";", "").Replace("#", ""))
                                    .Replace(" ", "").Replace("&", "").Replace(";", "").Replace("#", "") + ".aspx";

                                this.flArticleBody.SaveAs(ConfigurationManager.AppSettings["FileRepository"].ToString() +
                                    _ArticlePath);

                                _article.AllowedToPublish = (bool)Session["UserLevel"];
                                _article.Publish_Date = DateTime.Today;
                                _article.Publisher_ID = (int)Session["UserID"];
                                _article.Short_Description = this.txtShortDescription.Text.Trim();
                                _article.Title = title;

                                if (!string.IsNullOrEmpty(_technologies))
                                    _article.Technologies = ConvertArrayToPair(_technologies.Split(','));
                                if (!string.IsNullOrEmpty(_skills))
                                    _article.Skills = ConvertArrayToPair(_skills.Split(','));
                                if (!string.IsNullOrEmpty(_platforms))
                                    _article.Platforms = ConvertArrayToPair(_platforms.Split(','));
                                if (!string.IsNullOrEmpty(_languages))
                                    _article.Languages = ConvertArrayToPair(_languages.Split(','));
                                //_article.Tags = ConvertArrayToPairTag(this.txtTags.Text.Trim().Split(','));
                                _article.Path = _ArticleForDB;

                                int _articleID = _service.PublishArticle(_article);
                                if (this.chkSendWarnings.Checked)
                                {
                                    _service.MarkForFollowArticle(_articleID, (int)Session["UserID"], true);
                                }

                                try
                                {
                                    MailMessage _message = new MailMessage();
                                    _message.From = new MailAddress("no-reply@preguntaalexperto.net", "Pregunta Al Experto");
                                    _message.IsBodyHtml = true;
                                    _message.Subject = "Se ha publicado un nuevo artículo";
                                    _message.To.Add(new MailAddress("info@preguntaalexperto.net"));
                                    _message.Body = "Se ha publicado un nuevo artículo.\n\n" +
                                        "Para moderar, el nombre del artículo es: " + _ArticlePath + "para ver el comentario.";
                                    SmtpClient _sender = new SmtpClient("mail.preguntaalexperto.net");
                                    _sender.UseDefaultCredentials = false;
                                    _sender.Credentials = new NetworkCredential("info@preguntaalexperto.net", "ppgmz555");
                                    _sender.Send(_message);
                                }
                                catch
                                { }

                                this.pnlThanksForPublish.Visible = true;
                                this.pnlPublish.Visible = false;
                            }
                            catch (Exception ex)
                            {
                                this.lblHeaderError.Visible = true;
                                this.lblHeaderError.Text = "Se produjo un error al tratar de publicar su artículo.";
                            }

                        }
                        else
                        {
                            this.lblHeaderError.Text = Resources.language.ErrorSelectArticleFile;
                            this.lblHeaderError.Visible = true;
                        }
                    }
                    else
                    {
                        this.lblHeaderError.Text = Resources.language.ErrorCommonArticleHeader;
                        this.lblHeaderError.Visible = true;
                    }
                //}
            //    else
            //    {
            //        this.lblErrorCategories.Visible = true;
            //    }
            //}
            //else
            //{
            //    this.lblErrorCategories.Visible = true;
            //}
        }

        public List<PreguntaAlExperto.RulesLayer.Entities.Pair> ConvertArrayToPair(string[] _pairList)
        {
            List<PreguntaAlExperto.RulesLayer.Entities.Pair> _list = new List<PreguntaAlExperto.RulesLayer.Entities.Pair>();
            foreach (string Element in _pairList)
            {
                if (Element.Trim().Length != 0)
                {
                    PreguntaAlExperto.RulesLayer.Entities.Pair _pair = new PreguntaAlExperto.RulesLayer.Entities.Pair();
                    _pair.ID = int.Parse(Element);
                    _list.Add(_pair);
                }
            }
            return _list;
        }

    }
}
